import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-20
 * Time: 20:36
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverPort = serverPort;
        this.serverIp = serverIp;
    }
    public void start() throws IOException {
        //从控制台读取用户输入的数据
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的内容");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2.构造请求数据包， 把数据包发给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp)
            , serverPort);
            //3.发送数据包
            socket.send(requestPacket);
            //4.接受服务器的处理
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
